package org.lzuploader.gui.listeners.servers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Shell;
import org.lzuploader.gui.WServers;
import org.lzuploader.model.Config;

/** This class is used when user changes the name in server window.
 * 
 * @author Emmanuel Cron
 *
 */
public class NameModifyListener implements ModifyListener
{
    /** The logger for this class. */
    private static Log log = LogFactory.getLog(NameModifyListener.class);
    
    /** Called when user modifies the widget.
     * @param e Associated event
     */
    @Override
    public void modifyText(final ModifyEvent e)
    {
        log.debug("User has modified the name widget in the window.");
        
        log.trace("Fetching data.");
        
        Shell wServersShell = null;
        for (int i = 0 ; i < e.display.getShells().length ; i++)
        {
            if (e.display.getShells()[i].getData() instanceof WServers)
            {
                wServersShell = e.display.getShells()[i];
                break;
            }
        }
        
        final Object data = wServersShell.getData();
        WServers servers;
        
        if (data instanceof WServers)
        {
            servers = (WServers) data;
        }
        else
        {
            log.trace("getData() is not an instance of WServers. Returning.");
            return;
        }
        
        final String name = servers.getNameWidget().getText();
        final Config config = Config.getInstance();
        
        log.trace("Checking if name already exists: " + name);
        
        for (String server : config.getServers().keySet())
        {
            if (server.equalsIgnoreCase(name))
            {
                log.trace("Name found. Disabling buttons if needed.");
                
                if (servers.getTestButton().getEnabled())
                {
                    servers.getTestButton().setEnabled(false);
                }
                
                if (servers.getAddButton().getEnabled())
                {
                    servers.getAddButton().setEnabled(false);
                }
                
                return;
            }
        }
        
        log.trace("Name not found. Enabling buttons if needed.");
        
        if (!servers.getTestButton().getEnabled())
        {
            servers.getTestButton().setEnabled(true);
        }
    }

}
